<template>
    <el-form ref="form" :rules="rules" :model="form" label-width="100px" class="mt-10">
        <el-row>
            <el-col :span="14">
                <el-form-item label="页面类型" prop="type">
                    <el-select v-model="form.type" class="filter-item" placeholder="页面类型" style="width: 160px;">
                        <el-option
                            v-for="(item, index) in options.types"
                            :key="index"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="页面名称" prop="name">
                    <el-input v-model="form.name" placeholder="页面名称"></el-input>
                </el-form-item>
                <el-form-item label="地址前缀">
                    {{ $CDN_SITE_URL }}
                </el-form-item>
                <el-form-item label="页面路径" prop="path">
                    <el-input v-model="form.path" placeholder="页面路径, 相对路径或完整URL"></el-input>
                </el-form-item>
                <el-form-item label="是否默认">
                    <el-switch v-model="form.is_default" :active-value="true" :inactive-value="false" active-color="#13ce66"></el-switch>
                </el-form-item>
                <el-form-item label="渠道" v-if="!form.is_default">
                    <el-card class="role-access-card" shadow="hover" v-for="(typeItem, typeIndex) in appSourceOptions.type" :key="typeIndex" v-if="appSourceGroupByType[typeIndex]">
                        <div slot="header" class="clearfix">
                            <el-checkbox
                                v-model="selectedAll[typeIndex]"
                                @change="handleCheckAllChange($event, typeIndex)"
                                :indeterminate="isIndeterminate[typeIndex]">
                                {{ typeItem.label }}
                            </el-checkbox>
                        </div>

                        <template>
                            <el-checkbox-group v-model="form.sources">
                                <el-checkbox
                                    @change="handleCheckedChange($event, typeIndex)"
                                    v-for="(item, index) in appSourceGroupByType[typeIndex]"
                                    :label="item.id"
                                    :key="index">
                                    {{ item.id }} ) {{ item.name }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </template>
                    </el-card>
                </el-form-item>

            </el-col>

            <el-col :span="10">
                <el-form-item label="预览">
                    <iframe :src="pageUrl" frameborder="0" style="width: 450px;height: 75vh;"></iframe>
                </el-form-item>
            </el-col>
            <el-col>
                <el-form-item>
                    <el-button type="primary" :loading="loading" @click="submit">确定</el-button>
                    <el-button @click="cancel">返回</el-button>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</template>

<script>
export default {
    props: {
        data: {}
    },
    components: {

    },
    data() {
        return {
            loading: false,
            form: {},
            formDefault: {
                id: '',
                type: '',
                name: '',
                path: '',
                is_default: false,
                sources: [],
            },
            rules: {
                // source: {required: true, message: '请选择应用渠道', trigger: 'blur',},
                type: {required: true, message: '请选择页面类型', trigger: 'blur',},
                name: {required: true, message: '请输入页面名称', trigger: 'blur',},
                path: {required: true, message: '请输入页面路径', trigger: 'blur',},
            },
            options: this.$store.state.appWebpage.options,
            isCreate: true,
            selectedAll: {},
            isIndeterminate: {},
            appSourceOptions: this.$store.state.appSource.options,
        }
    },
    computed: {
        appSources () {
            return this.$store.state.appSource.all;
        },
        appSourceGroupByType() {
            // 将渠道按类型分组
            let groups = {};
            this.$store.state.appSource.all.map(v => {
                if (!groups[v.type]) {
                    groups[v.type] = [v];
                } else {
                    groups[v.type].push(v);
                }
            });
            return groups;
        },
        pageUrl() {
            if (!this.form.path) return "";
            if (this.form.path.indexOf('http://') > -1 || this.form.path.indexOf('https://') > -1) return this.form.path;
            return this.$CDN_SITE_URL + this.form.path;
        }
    },
    watch: {
        data(newVal) {
            this.syncForm();
        },
    },
    methods: {
        getFormAction() {
            return this.isCreate ? 'appWebpage/Store' : 'appWebpage/Update';
        },
        submit() {
            this.$refs.form.validate(valid => {
                if (!valid) return false;

                // 默认页面的话 不需要设置渠道
                let form = this.$helper.deepClone(this.form);
                if (form.is_default) form.sources = [];

                this.loading = true;
                this.$store.dispatch(this.getFormAction(), form).then(res => {
                    this.$message.success(res.data.message);
                    this.$emit('submit');
                }).finally(() => {
                    this.loading = false;
                });
            });
        },
        cancel() {
            this.$emit('cancel');
        },
        syncForm() {
            this.form = this.$helper.deepClone(Object.assign({}, this.data.id ? this.data : this.formDefault));
            this.isCreate = this.form.id <= 0;

            // 渠道默认选中
            Object.keys(this.appSourceOptions.type).map(k => {
                this.handleCheckedChange(true, k);
            });
        },
        // 顶级权限选中|取消, 自动选中|取消子级权限
        handleCheckAllChange(val, pKey) {
            this.isIndeterminate[pKey] = false;
            let typeItem = this.appSourceOptions.type[pKey];
            if (val) {
                this.appSources.map(v => {
                    if (typeItem.value === v.type && this.form.sources.indexOf(v.id) === -1) this.form.sources.push(v.id);
                });
            } else {
                this.appSources.map(v => {
                    if (typeItem.value === v.type && this.form.sources.indexOf(v.id) > -1)this.form.sources.splice(this.form.sources.indexOf(v.id), 1);
                });
            }
        },
        // 子级选中|取消, 检查顶级权限是否需要选中|取消
        handleCheckedChange(val, pKey) {
            let typeItem = this.appSourceOptions.type[pKey];
            let childArr = this.appSources.filter(v => { return v.type === typeItem.value; }).map(v => v.id);
            let checkedLength = this.form.sources.filter(v => childArr.includes(v)).length;
            this.isIndeterminate[pKey] = checkedLength > 0 && checkedLength < childArr.length;
            this.selectedAll[pKey] = childArr.length && checkedLength === childArr.length;
        },
    },
    created() {
        this.syncForm();
    }
}
</script>

<style lang="scss" scoped>
.item-row {
    margin: 0 0 10px 0;
}
</style>

